package com.jxc.wiki.controller;

import com.jxc.wiki.request.DocQueryParamReq;
import com.jxc.wiki.request.DocSaveParamReq;
import com.jxc.wiki.response.DocQueryParamResp;
import com.jxc.wiki.response.CommonResp;
import com.jxc.wiki.response.PageParamResp;
import com.jxc.wiki.service.DocService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

@Controller
public class DocController {

    @Resource
    private DocService docService;

    // 测试get请求
    @RequestMapping("/doc/all/{ebookId}")
    @ResponseBody
    // @Valid 用来开启校验，防止有人通过脚本修改后端获取的数据数，从而导致服务器崩溃
    public CommonResp<List<DocQueryParamResp>> all(@PathVariable Long ebookId){
        CommonResp<List<DocQueryParamResp>> resp = new CommonResp<>();
        List<DocQueryParamResp> list = docService.all(ebookId);
        resp.setContent(list);
        return resp;
    }

    @PostMapping("/doc/save")
    @ResponseBody
    // 注意由于axios的post请求提交是用json的格式，所以在参数前要加个@RequestBody，相当于标记数据为application/json格式
    public CommonResp<Object> save(@Valid @RequestBody DocSaveParamReq req){
        CommonResp<Object> resp = new CommonResp<>();
        docService.save(req);
        return resp;
    }


    @DeleteMapping("/doc/delete/{idsStr}")
    @ResponseBody
    public CommonResp<Object> delete(@PathVariable String idsStr){
        CommonResp<Object> resp = new CommonResp<>();
        List<String> list = Arrays.asList(idsStr.split(","));
        docService.delete(list);
        return resp;
    }

    // 测试get请求
    @RequestMapping("/doc/search")
    @ResponseBody
    // @Valid 用来开启校验，防止有人通过脚本修改后端获取的数据数，从而导致服务器崩溃
    public CommonResp<PageParamResp<DocQueryParamResp>> search(@Valid DocQueryParamReq req){
        CommonResp<PageParamResp<DocQueryParamResp>> resp = new CommonResp<>();
        PageParamResp<DocQueryParamResp> list = docService.list(req);
        resp.setContent(list);
        return resp;
    }

    @RequestMapping("/doc/find-content/{id}")
    @ResponseBody
    // @Valid 用来开启校验，防止有人通过脚本修改后端获取的数据数，从而导致服务器崩溃
    public CommonResp<String> findContent(@PathVariable Long id){
        CommonResp<String> resp = new CommonResp<>();
        String content = docService.findContent(id);
        resp.setContent(content);
        return resp;
    }

    @GetMapping("/doc/vote/{id}")
    @ResponseBody
    public CommonResp<Object> vote(@PathVariable Long id){
        CommonResp<Object> resp = new CommonResp<>();
        docService.vote(id);
        return resp;
    }
}
